import axios from 'axios'
import { Modal } from 'antd'
import { globalConfig } from '@/globalConfig'

// 用户登录信息在localStorage中存放的名称
export const SESSION_LOGIN_INFO = globalConfig.SESSION_LOGIN_INFO

let API_DOMAIN = '/api/'

if(import.meta.env.MODE === 'prodution') {
  API_DOMAIN = '/des/api/'
}

const service = axios.create({
  timeout: 600000
})

service.interceptors.request.use(
  config => {
    let info = window.localStorage.getItem(SESSION_LOGIN_INFO)
    if(info) {
      const { token } = JSON.parse(info)
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  err => {
    var error = { error: err }
    if (!err.response) {
      error.message = '网络异常！请稍后再试'
    } else if (err.response.status == 401) {
      error.message = '登录失效或已登录超时，请重新登录'
      if (window.parent) {
        if(window.__MicroService) {
          window.__MicroService.dispatch("logout")
        }
      }
    } else if (err.response.status == 403) {
      error.message = '你没有访问该数据的权限!'
    } else if (err.response.status == 504 || err.response.status == 404) {
      error.message = '服务器异常！请重试或联系在线客服'
    } else {
      error.message = '未知错误！'
    }
    Modal.error({
      title: error.message,
    })
    return Promise.reject(error)
  }
)

export default service
